package cn.wjx.taobaounion.ui.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import cn.wjx.taobaounion.model.domain.CategoryContent;
import cn.wjx.taobaounion.utils.URLUtils;

/**
 * @author WuChangJian
 * @date 2020/6/19 17:21
 */
public class LooperPagerAdapter extends PagerAdapter {

    private List<CategoryContent.DataBean> mList = new ArrayList<>();
    private OnLooperPagerClickListener mOnLooperPagerClickListener;

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        int realPosition = position % mList.size();
        String pictUrl = mList.get(realPosition).getPict_url();
        ImageView iv = new ImageView(container.getContext());
        // 无法获取到iv的宽高，因为LayoutParams.MATCH_PARENT = -1,所以获取container容器的宽高
        int measuredHeight = container.getMeasuredHeight();
        int measuredWidth = container.getMeasuredWidth();
        int looperSize = (measuredWidth > measuredHeight ? measuredWidth : measuredHeight) / 2;
        Glide.with(container.getContext()).load(URLUtils.getCoverPath(pictUrl, looperSize)).into(iv);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        iv.setLayoutParams(layoutParams);
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        iv.setOnClickListener(v -> {
            if (mOnLooperPagerClickListener != null) {
                mOnLooperPagerClickListener.onLooperPagerClick(mList.get(realPosition));
            }
        });
        container.addView(iv);
        return iv;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    public void setData(List<CategoryContent.DataBean> contents) {
        mList.clear();
        mList.addAll(contents);
        notifyDataSetChanged();
    }

    public interface OnLooperPagerClickListener {
        void onLooperPagerClick(CategoryContent.DataBean item);
    }

    public void setOnLooperPagerClickListener(OnLooperPagerClickListener listener) {
        this.mOnLooperPagerClickListener = listener;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    public int getDataSize() {
        return mList.size();
    }
}
